/*jshint esversion: 6 */

const config = require('../config.js');
const _ = require('./lodash.js');


/**
 * [getNodes description]
 * @param  {[type]} className [description]
 * @param  {[type]} options   [description]
 * @return {[type]}           [description]
 */

function checkNodeType(className) {
    if (!className || !_.isString(className)) {
        console.error('className必填且为字符串类型');
        return false;
    }
    if (_.indexOf(config.nodeType, className) === -1) {
        console.error('支持的className', config.nodeType, '若要新增', className, '需在config.js中nodeType中增加');
        return false;
    }
    return true;
}

function request(option) {
    return new Promise((resolve, reject) => {
        wx.request({
            url: option.url,
            header: {
                'X-Parse-Application-Id': config.api.appId,
            },
            method: option.method,
            data: option.data,
            success: (res) => resolve(res.data),
            fail: (err) => reject(err)
        });
    });
}


/**
 * [get description]
 * @param  {[type]} className [description]
 * @param  {[type]} options   [description]
 * @return {[type]}           [description]
 */
// 使用示例:
// request.getNodes('goods', {
//         query: '{"like": { "$gte": 100 }}',
//         order: '-like',
//         page: 1,
//         keys: 'title,price'
//     })
//     .then((res) => {
//         this.setData({
//             loading: false,
//             lists: res.results
//         });
//     })
//     .catch((error) => {
//         console.log(error);
//     });
function get(className, options) {
    if (!checkNodeType(className)) {
        return;
    }
    let params = '';
    let paging = {};
    if (options && _.isObject(options)) {
        if (options.page && options.page > 0) {
            let maxPerPage = config.maxPerPage || 10;
            paging.limit = maxPerPage;
            paging.skip = (options.page - 1) * maxPerPage;
        } else if (options.page) {
            console.error('page必须为大于0的整数');
            return;
        }
        let limit = (paging.limit) ? 'limit=' + paging.limit : null;
        let skip = (paging.skip) ? 'skip=' + paging.skip : null;
        let query = (options.query) ? 'where=' + encodeURIComponent(options.query) : null;
        let order = (options.order) ? 'order=' + options.order : null;
        let keys = (options.keys) ? 'keys=' + options.keys : null;
        _.compact([query, limit, order, skip, keys]).map((param, index) => {
            if (index === 0) {
                params += '?' + param;
                return;
            }
            params += '&' + param;
        });
    } else if (options && _.isString(options)) {
        params = '/' + options;
    }
    let url = config.api.host + '/classes/' + className + params;
    return request({
        url: url,
        method: 'GET',
    });
}


function post(className, data) {
    if (!checkNodeType(className)) {
        return;
    }
    let url = config.api.host + '/classes/' + className;
    return request({
        url: url,
        method: 'POST',
        data: data
    });
}

function put(className, objectId, data) {
    let url = config.api.host + '/classes/' + className + '/' + objectId;
    return request({
        url: url,
        method: 'PUT',
        data: data
    });
}

function del(className, objectId) {
    return request({
        url: url,
        method: 'DELETE'
    });
}


function getStorage(key) {
    return new Promise((resolve, reject) => {
        wx.getStorage({
            key: key,
            success: (res) => resolve(res.data),
            fail: (err) => reject(err)
        });
    });
}


function wxGetUserInfo() {
    return new Promise((resolve, reject) => {
        let localUserInfo = wx.getStorageSync('userInfo');
        if (localUserInfo) {
            resolve(localUserInfo);
        } else {
            wxLogin().then(() => {
                wx.getUserInfo({
                    success: (res) => {
                        wx.setStorageSync('userInfo', res.userInfo);
                        resolve(res.userInfo);
                    },
                    fail: (err) => reject(err)
                });
            });
        }
    });

}

function wxLogin() {
    return new Promise((resolve, reject) => {
        wx.login({
            success: function(res) {
                if (res.code) {
                    resolve(res.code);
                } else {
                    reject(res.errMsg);
                }
            },
            fail: (err) => reject(err)
        });
    });
}


const xman = {
    get: get,
    post: post,
    put: put,
    del: del,
    getStorage: getStorage,
    wxGetUserInfo: wxGetUserInfo,
    wxLogin: wxLogin
};
module.exports = xman;
